package com.example.zhihuigongdi.commer.common.security;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.example.zhihuigongdi.commer.IgnoredUrlsProperties;
import com.example.zhihuigongdi.commer.common.enums.SecurityEnum;
import com.example.zhihuigongdi.entity.User;
import com.example.zhihuigongdi.utils.JwtUtil;
import com.example.zhihuigongdi.utils.RedisCache;
import com.example.zhihuigongdi.utils.ResponseUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 认证结果过滤器
 *
 * @author Chopper
 * @version v4.1
 * @since 2020/11/17 3:37 下午
 * @since
 */
@Slf4j
public class AuthenticationFilter extends BasicAuthenticationFilter {


    /**
     * 缓存
     */
    @Autowired
    private RedisCache cache;

    private IgnoredUrlsProperties ignoredUrlsProperties;


    /**
     * 自定义构造器
     *
     * @param authenticationManager
     * @param cache
     */
    public AuthenticationFilter(AuthenticationManager authenticationManager,
                                RedisCache cache,
    IgnoredUrlsProperties ignoredUrlsProperties) {
        super(authenticationManager);
        this.cache = cache;
        this.ignoredUrlsProperties=ignoredUrlsProperties;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //从header中获取jwt
        String jwt = request.getHeader(SecurityEnum.HEADER_TOKEN.getValue());
        try {
//            如果没有token 则return
            if (StrUtil.isBlank(jwt)|| jwt.equals("null")) {

//                return;
                StringBuffer requestURL = request.getRequestURL();

                List<String> collect = ignoredUrlsProperties.getUrls().stream().filter(url -> requestURL.toString().contains(url)).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(collect)){
//                    ResponseUtil.output(response, 409, ResponseUtil.resultMap(false, 409, "未登录"));
//                    return;
                }
                chain.doFilter(request, response);
                return;


//                for (String url : ignoredUrlsProperties.getUrls()) {
//                    if (request.getRequestURL().toString().contains(url)) {
//                        return;
//                    }
//                }
//                ResponseUtil.output(response, 407, ResponseUtil.resultMap(false, 409, "未登录"));
//                return;
            }
//            获取用户信息，存入context
            UsernamePasswordAuthenticationToken authentication = getAuthentication(jwt, response);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (Exception e) {
            log.error("BuyerAuthenticationFilter-> member authentication exception:", e);
        }
        chain.doFilter(request, response);
    }

    /**
     * 解析用户
     *
     * @param jwt
     * @param response
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(String jwt, HttpServletResponse response) {

        String userid;
        try {
            Claims claims
                    = JwtUtil.parseJWT(jwt);
            //获取存储在claims中的用户信息
            userid = claims.getSubject();

           String redisKey="login:"+userid;
            //校验redis中是否有权限
            User user = cache.getCacheObject(redisKey);
            if (!Objects.isNull(user)) {
                //构造返回信息
                List<GrantedAuthority> auths = new ArrayList<>();
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getAccount(), null, auths);
                authentication.setDetails(user);
                return authentication;
            }
            ResponseUtil.output(response, 403, ResponseUtil.resultMap(false, 403, "登录已失效，请重新登录"));
            return null;
        } catch (ExpiredJwtException e) {
            log.debug("user analysis exception:", e);
        } catch (Exception e) {
            log.error("user analysis exception:", e);
            ResponseUtil.output(response, 403, ResponseUtil.resultMap(false, 403, "token错误，请不要搞我QAQ"));

        }
        return null;
    }

}

